<?php

namespace App\Http\Controllers\Util;

use App\User;
use Houdunwang\Aliyun\Aliyun;
use App\Notifications\RegisterNotify;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CodeController extends Controller
{
    protected $expire;
    public function __construct()
    {
        $this->expire = cache_config('code.code_expire');
    }

    //过期时间

    public function send(Request $request){

        $code  = code_radom();
        if(filter_var($request->username,FILTER_VALIDATE_EMAIL)){
            //是邮箱
            $type = 'email';
            $email = User::where('email',$request->username)->first();
            if($email){
                return ['code' => 0, 'message' => '邮箱已存在'];

            }
            $user = User::firstOrNew ( [ 'email' => $request->username ] );
            $user->notify ( new RegisterNotify( $code ) );

        }else{
            //是手机
            $type = 'mobile';
            $data = [
                //短信签名
                'sign'     => 'laravel社区',
                //短信模板
                'template' => 'SMS_144151107',
                //前台提交来的手机号码
                'mobile'   => $request->username,
                //模板变量
                'vars'     => ["code" => $code],
            ];
            $phone = User::where('phone',$request->username)->first();
            if($phone){
                return ['code' => 0, 'message' => '手机号已经存在'];
            }
            $res = Aliyun::instance('Sms')->send($data);
        }
        $this->SavetoSession($code,$type,$request->username);
        return ['code' => 1, 'message' => '发送成功'];
    }

    //将验证码储存到 session中
    public function SavetoSession($code,$type,$username){

        session()->put('valid_code',[
            'code'=>$code,
            'type'=>$type,
            'username'=>$username,
            'expire'=>time()+ $this->expire,
        ]);
    }
}
